<template>
  <div class="task-container">
         <!-- 页面标题 -->
     <div class="page-header">
       <h2>
         <el-icon class="page-icon"><Grid /></el-icon>
         当前任务
       </h2>
     </div>

         <!-- 搜索和操作栏 -->
     <div class="search-action-bar">
               <div class="search-area">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="工单编号"
            clearable
            style="width: 200px; margin-right: 10px;"
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          />
                     <el-button type="primary" @click="handleSearch">
             <el-icon><Search /></el-icon>查询
           </el-button>
           <el-button type="primary" @click="toggleAdvancedSearch">
             <el-icon><Search /></el-icon>高级查询
           </el-button>
        </div>
       
       <div class="view-toggle">
         <el-button type="text" @click="toggleViewMode">
           <el-icon><Grid /></el-icon>
         </el-button>
       </div>
     </div>

     <!-- 高级查询表单（内联展开式） -->
     <div v-show="advancedSearchVisible" class="advanced-search-panel">
       <el-form :model="advancedSearchForm" label-width="120px" class="advanced-search-form">
         <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工单编号">
              <el-input v-model="advancedSearchForm.orderNo" placeholder="工单编号" clearable />
            </el-form-item>
          </el-col>
        </el-row>
         
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="计划数">
               <el-input-number v-model="advancedSearchForm.plannedQty" :min="0" :max="999999" style="width: 100%" controls-position="right" />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="良品数">
               <el-input-number v-model="advancedSearchForm.goodQty" :min="0" :max="999999" style="width: 100%" controls-position="right" />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="不良品数">
               <el-input-number v-model="advancedSearchForm.badQty" :min="0" :max="999999" style="width: 100%" controls-position="right" />
             </el-form-item>
           </el-col>
         </el-row>
         
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="计划开始时间">
               <el-date-picker
                 v-model="advancedSearchForm.plannedStartTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="计划结束时间">
               <el-date-picker
                 v-model="advancedSearchForm.plannedEndTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="创建时间">
               <el-date-picker
                 v-model="advancedSearchForm.createTimeRange"
                 type="datetimerange"
                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 format="YYYY-MM-DD HH:mm:ss"
                 value-format="YYYY-MM-DD HH:mm:ss"
                 style="width: 100%"
               />
             </el-form-item>
           </el-col>
         </el-row>
         
         <div class="advanced-search-actions">
           <el-button type="primary" @click="handleAdvancedSearchSubmit" class="search-btn">
             <el-icon><Search /></el-icon>查询
           </el-button>
           <el-button type="success" @click="handleAdvancedSearchReset" class="reset-btn">
             <el-icon><Refresh /></el-icon>重置
           </el-button>
           <el-button @click="toggleAdvancedSearch" class="close-btn">
             <el-icon><Close /></el-icon>关闭
           </el-button>
         </div>
       </el-form>
     </div>

         <!-- 任务表格 -->
     <div class="table-container">
               <el-table
          :data="taskList"
          v-loading="loading"
          style="width: 100%; height: calc(100% - 60px)"
          border
          stripe
          highlight-current-row
        >
         
         <el-table-column type="index" label="#" width="60" align="center" />
       <el-table-column prop="orderNo" label="工单编号" width="160" />
         
         <el-table-column prop="plannedStartTime" label="计划开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.plannedStartTime) }}
          </template>
        </el-table-column>
         <el-table-column prop="plannedEndTime" label="计划结束时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.plannedEndTime) }}
           </template>
         </el-table-column>
         <el-table-column prop="plannedQty" label="计划数" width="100" align="center" />
         <el-table-column prop="goodQty" label="良品数" width="100" align="center" />
         <el-table-column prop="badQty" label="不良品数" width="100" align="center" />
         <el-table-column prop="actualStartTime" label="实际开始时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.actualStartTime) }}
           </template>
         </el-table-column>
         <el-table-column prop="actualEndTime" label="实际结束时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.actualEndTime) }}
           </template>
         </el-table-column>
         <el-table-column prop="createTime" label="创建时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.createTime) }}
           </template>
         </el-table-column>
         <el-table-column prop="creator" label="创建人" width="120" />
         <el-table-column prop="modifier" label="修改人" width="120" />
         <el-table-column prop="modifyTime" label="修改时间" width="180">
           <template #default="scope">
             {{ formatDateTime(scope.row.modifyTime) }}
           </template>
         </el-table-column>
       </el-table>
       
       <!-- 分页 -->
       <div class="pagination-container">
         <el-pagination
           :current-page="pagination.pageIndex"
           :page-size="pagination.pageSize"
           :page-sizes="[10, 20, 30, 50]"
           :total="pagination.totalCount"
           layout="total, sizes, prev, pager, next, jumper"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
         />
       </div>
     </div>

    

    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Grid, Search, Refresh, Close } from '@element-plus/icons-vue'
import { getTaskPageList, getTaskAdvancedPageList, type Task, type TaskQueryParams, type TaskAdvancedQueryParams } from '@/api/task'

// 响应式数据
const loading = ref(false)
const taskList = ref<Task[]>([])
const viewMode = ref<'table' | 'grid'>('table')

// 搜索表单
const searchForm = reactive({
  orderNo: ''
})

// 高级搜索表单
const advancedSearchForm = reactive({
  orderNo: '',
  taskName: '',
  taskCode: '',
  defectiveItemList: '',
  plannedQty: 0,
  goodQty: 0,
  badQty: 0,
  plannedStartTimeRange: [] as string[],
  plannedEndTimeRange: [] as string[],
  actualStartTimeRange: [] as string[],
  actualEndTimeRange: [] as string[],
  createTimeRange: [] as string[]
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

// 对话框显示状态
const advancedSearchVisible = ref(false)

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true
  try {
    const params: TaskQueryParams = {
      orderNo: searchForm.orderNo, // 使用工单编号作为查询条件
      pageIndex: pagination.pageIndex, // 后端从1开始
      pageSize: pagination.pageSize
    }
    
    const response = await getTaskPageList(params)
    if (response.data.code === 200) {
      const data = response.data.data || {}
      // 兼容后端返回的 PascalCase 与 camelCase（外层与每项字段）
      const rawList = (data.tasks ?? data.Tasks) || []
      taskList.value = rawList.map((item: any) => ({
        // 基本字段统一
        taskId: item.taskId ?? item.TaskId,
        orderNo: item.orderNo ?? item.OrderNo,
        defectItemId: item.defectItemId ?? item.DefectItemId,
        taskName: item.taskName ?? item.TaskName,
        taskCode: item.taskCode ?? item.TaskCode,
        workPermission: item.workPermission ?? item.WorkPermission,
        reportQtyRatio: item.reportQtyRatio ?? item.ReportQtyRatio,
        reportTime: item.reportTime ?? item.ReportTime,
        defectiveItemList: item.defectiveItemList ?? item.DefectiveItemList,
        allocationList: item.allocationList ?? item.AllocationList,
        plannedStartTime: item.plannedStartTime ?? item.PlannedStartTime,
        plannedEndTime: item.plannedEndTime ?? item.PlannedEndTime,
        plannedQty: item.plannedQty ?? item.PlannedQty,
        goodQty: item.goodQty ?? item.GoodQty,
        badQty: item.badQty ?? item.BadQty,
        actualStartTime: item.actualStartTime ?? item.ActualStartTime,
        actualEndTime: item.actualEndTime ?? item.ActualEndTime,
        creator: item.creator ?? item.Creator,
        createTime: item.createTime ?? item.CreateTime,
        modifier: item.modifier ?? item.Modifier,
        modifyTime: item.modifyTime ?? item.ModifyTime,
      }))
      pagination.totalCount = data.totalCount ?? data.TotalCount ?? 0
      // 同步页码与页大小（若后端返回）
      const currentPage = data.currentPage ?? data.CurrentPage
      const pageSize = data.pageSize ?? data.PageSize
      if (typeof currentPage === 'number') pagination.pageIndex = currentPage
      if (typeof pageSize === 'number') pagination.pageSize = pageSize
    } else {
      ElMessage.error(response.data.msg || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchTaskList()
}

// 高级搜索
const handleAdvancedSearch = () => {
  advancedSearchVisible.value = true
}

// 切换高级搜索面板
const toggleAdvancedSearch = () => {
  advancedSearchVisible.value = !advancedSearchVisible.value
}

// 高级搜索提交
const handleAdvancedSearchSubmit = async () => {
  try {
    // 构建高级查询参数
    const params: TaskAdvancedQueryParams = {
      orderNo: advancedSearchForm.orderNo || undefined,
      defectiveItemList: advancedSearchForm.defectiveItemList || undefined,
      plannedQty: advancedSearchForm.plannedQty || undefined,
      goodQty: advancedSearchForm.goodQty || undefined,
      badQty: advancedSearchForm.badQty || undefined,
      plannedStartTimeFrom: advancedSearchForm.plannedStartTimeRange[0] || undefined,
      plannedStartTimeTo: advancedSearchForm.plannedStartTimeRange[1] || undefined,
      plannedEndTimeFrom: advancedSearchForm.plannedEndTimeRange[0] || undefined,
      plannedEndTimeTo: advancedSearchForm.plannedEndTimeRange[1] || undefined,
      actualStartTimeFrom: advancedSearchForm.actualStartTimeRange[0] || undefined,
      actualStartTimeTo: advancedSearchForm.actualStartTimeRange[1] || undefined,
      actualEndTimeFrom: advancedSearchForm.actualEndTimeRange[0] || undefined,
      actualEndTimeTo: advancedSearchForm.actualEndTimeRange[1] || undefined,
      createTimeFrom: advancedSearchForm.createTimeRange[0] || undefined,
      createTimeTo: advancedSearchForm.createTimeRange[1] || undefined,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    loading.value = true
    const response = await getTaskAdvancedPageList(params)
    if (response.data.code === 200) {
      const data = response.data.data || {}
      const rawList = (data.tasks ?? data.Tasks) || []
      taskList.value = rawList.map((item: any) => ({
        taskId: item.taskId ?? item.TaskId,
        orderNo: item.orderNo ?? item.OrderNo,
        defectItemId: item.defectItemId ?? item.DefectItemId,
        taskName: item.taskName ?? item.TaskName,
        taskCode: item.taskCode ?? item.TaskCode,
        workPermission: item.workPermission ?? item.WorkPermission,
        reportQtyRatio: item.reportQtyRatio ?? item.ReportQtyRatio,
        reportTime: item.reportTime ?? item.ReportTime,
        defectiveItemList: item.defectiveItemList ?? item.DefectiveItemList,
        allocationList: item.allocationList ?? item.AllocationList,
        plannedStartTime: item.plannedStartTime ?? item.PlannedStartTime,
        plannedEndTime: item.plannedEndTime ?? item.PlannedEndTime,
        plannedQty: item.plannedQty ?? item.PlannedQty,
        goodQty: item.goodQty ?? item.GoodQty,
        badQty: item.badQty ?? item.BadQty,
        actualStartTime: item.actualStartTime ?? item.ActualStartTime,
        actualEndTime: item.actualEndTime ?? item.ActualEndTime,
        creator: item.creator ?? item.Creator,
        createTime: item.createTime ?? item.CreateTime,
        modifier: item.modifier ?? item.Modifier,
        modifyTime: item.modifyTime ?? item.ModifyTime,
      }))
      pagination.totalCount = data.totalCount ?? data.TotalCount ?? 0
      const currentPage = data.currentPage ?? data.CurrentPage
      const pageSize = data.pageSize ?? data.PageSize
      if (typeof currentPage === 'number') pagination.pageIndex = currentPage
      if (typeof pageSize === 'number') pagination.pageSize = pageSize
      ElMessage.success('高级查询成功')
    } else {
      ElMessage.error(response.data.msg || '高级查询失败')
    }
  } catch (error) {
    console.error('高级查询失败:', error)
    ElMessage.error('高级查询失败')
  } finally {
    loading.value = false
  }
}

// 高级搜索重置
const handleAdvancedSearchReset = () => {
  Object.assign(advancedSearchForm, {
    orderNo: '',
    taskName: '',
    taskCode: '',
    defectiveItemList: '',
    plannedQty: 0,
    goodQty: 0,
    badQty: 0,
    plannedStartTimeRange: [],
    plannedEndTimeRange: [],
    actualStartTimeRange: [],
    actualEndTimeRange: [],
    createTimeRange: []
  })
}



// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchTaskList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchTaskList()
}

// 视图模式切换
const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'table' ? 'grid' : 'table'
}

// 不良品项点击
const handleDefectiveItemClick = (defectiveItemList: string) => {
  ElMessage.info(`查看不良品项: ${defectiveItemList}`)
}

// 分配列表点击
const handleAllocationClick = (allocationList: string) => {
  ElMessage.info(`查看分配列表: ${allocationList}`)
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTaskList()
})
</script>

<style scoped>
.task-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-icon {
  font-size: 20px;
  color: #666;
}

.search-action-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.view-toggle {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
  flex: 1;
  min-height: 400px;
  max-height: calc(100vh - 300px);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  background: white;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f0f9ff;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  text-align: center;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #409eff;
  color: white;
}

/* 高级查询面板样式 */
.advanced-search-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.advanced-search-form {
  padding: 0;
}

.advanced-search-form .el-form-item {
  margin-bottom: 20px;
}

.advanced-search-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}

.advanced-search-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0 0 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 0 0 0;
  border-top: 1px solid #e4e7ed;
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  font-weight: 500;
}

.search-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.reset-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
  font-weight: 500;
}

.reset-btn:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.close-btn {
  background-color: #909399;
  border-color: #909399;
  color: white;
  font-weight: 500;
}

.close-btn:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}



/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-input-number .el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-date-editor .el-input__wrapper) {
  border-radius: 4px;
}
</style>
